<?php

namespace app\common\model\service;

use app\common\model\BaseModel;
use app\common\model\hfztcy\LibCollect;
use app\common\model\hfztcy\LibConfig;
use app\common\model\hfztcy\LibStore;
use app\common\model\hfztcy\LibUserVideoAuth;
use app\common\model\LibUser;
use think\Db;

//公共函数

/**
 * 会员模块
 * @name LibMember.php
 * @package hfztcy
 * @category model
 * @link http://www.chanekeji.com
 * @author rxy
 * @version 1.0
 * @copyright CHANGE INC
 * @since 2022-06-17
 */
class LibMember extends BaseModel
{
    /**
     * Info: 会员列表
     * Date: 2022/11/17 15:31
     */
    public function pagingMemberList ($args,$page)
    {
        $videoAuthModel = new LibUserVideoAuth();
        $memberModel = new \app\common\model\hfztcy\LibMember();
        $configModel = new LibConfig();
        $collectModel = new LibCollect();
        $userModel = new LibUser();
        $storeModel = new LibStore();

        $form = $args['form'];

        // 排序
        $sort = 'add_time';

        // 条件筛选
        $where = [];
        $where[] = "`a`.`is_disabled` = 0";//只显示开启找对象
        $where[] = "`a`.`audit_state` = 1";//只显示审核成功的会员
        if (!empty($args['nick_name'])) $where[] = "`a`.`nick_name` like '%" . $args['nick_name'] . "%'";
        if (!empty($args['username'])) $where[] = "`a`.`username` like '%" . $args['username'] . "%'";
        //if (!empty($args['user_id'])) $where[] = "`a`.`user_id` <> '" . $args['user_id'] . "'";//不展示自己
        if (!empty($args['pid'])) $where[] = "`a`.`parent_id` = '" . $args['pid'] . "'";
        //if (!empty($args['sex'])) $where[] = "`a`.`sex` = '" . $args['sex'] . "'";
        if (!empty($args['phone'])) $where[] = "`a`.`mobile` = '" . $args['phone'] . "'";
        if (!empty($args['state'])) {//身份0游客1普通用户2vip会员3红娘4门店
            if ($args['state'] == 1) {
                $where1[] = "FIND_IN_SET(1,identity)";
                $where1[] = "FIND_IN_SET(2,identity)";
                $where[] = '('.implode(' OR ', $where1).')';
            } else {
                if ($args['state'] == 3) {
                    $sort = 'register_user_count';
                }
                $where[] = "FIND_IN_SET({$args['state']},identity)";
            }
        }
        if (!empty($args['is_vip_video'])) $where[] = "`a`.`is_vip_video` > 0";//普通会员与VIP会员 只展示已上传视频的用户
        if (!empty($args['is_red_mother_video'])) $where[] = "`a`.`is_red_mother_video` > 0";//红娘板块 只展示已上传视频的用户
        if (!empty($args['is_store_video'])) $where[] = "`a`.`is_store_video` > 0";//门店板块 只展示已上传视频的用户

        if ($form) {
            if (!empty($form['sex'])) $where[] = "`a`.`sex` = '" . $form['sex'] . "'";
            if (!empty($form['age']) && $form['age'] != '不限') {
                list($start,$end) = explode('~',$form['age']);
                $where[] = "`a`.`age` BETWEEN '" . $start . "' AND '" . $end . "'";
            }
            if (!empty($form['income']) && $form['income'] != '不限') $where[] = "`a`.`income` = '" . $form['income'] . "'";
            if (!empty($form['city'])) {
                $where[] = "`a`.`city` = '" . $form['city'] . "'";
            } else {
                $where[] = "`a`.`province` = '" . $form['province'] . "'";
            }
            if (!empty($form['marriage']) && $form['marriage'] != '不限') $where[] = "`a`.`marriage` = '" . $args['marriage'] . "'";
            if (!empty($form['educate']) && $form['educate'] != '不限') $where[] = "`a`.`educate` = '" . $args['educate'] . "'";
            if (!empty($form['height']) && $form['height'] != '不限') {
                list($start,$end) = explode('~',$form['height']);
                $where[] = "`a`.`height` BETWEEN '" . $start . "' AND '" . $end . "'";
            }
            if (!empty($form['weight']) && $form['weight'] != '不限') {
                list($start,$end) = explode('~',$form['weight']);
                $where[] = "`a`.`weight` BETWEEN '" . $start . "' AND '" . $end . "'";
            }
            if (!empty($form['is_children'])) $where[] = "`a`.`is_children` = '" . $args['is_children'] . "'";
            if (!empty($form['want_children'])) $where[] = "`a`.`want_children` = '" . $args['want_children'] . "'";
            if (!empty($form['is_house'])) $where[] = "`a`.`is_house` = '" . $args['is_house'] . "'";
            if (!empty($form['is_car'])) $where[] = "`a`.`is_car` = '" . $args['is_car'] . "'";
        } else {
            if (!empty($args['province']) && !empty($args['city'])) {//查询市区域
                $where[] = "`a`.`city` = '" . $args['city'] . "'";
            }
            if (!empty($args['province']) && empty($args['city'])) {//查询省区域
                $where[] = "`a`.`province` = '" . $args['province'] . "'";
            }
        }

        // 获取平台电话
        $findConfigRes = $configModel->findConfig(['item_key' => 'platform_mobile']);
        $mobile = $findConfigRes['data']['item_value'];

        // 分页
        $result = (new \app\common\model\hfztcy\LibMember())->pagingMember($page, implode(' AND ', $where),$sort);

        // 修改数据
        foreach ($result['data']['dataList'] as &$item) {
            // 会员身份
            $memberIdentity = [
                '游客',
                '注册用户',
                'vip会员',
                '红娘',
                '门店'
            ];
            // 身份
            $identityList = explode(',', $item['identity']);
            $identityList = array_map('intval', $identityList);
            foreach ($memberIdentity as $k => $v) {
                if (!in_array($k, $identityList)) {
                    unset($memberIdentity[$k]);
                }
            }
            $item['identity_text'] = implode("<br/>", $memberIdentity);
            $item['identity_list'] = array_values($memberIdentity);

            // 手机号码
            $item['my_mobile'] = $item['mobile'];

            // 默认照片
            $item['user_img'] = null;
            if ($item['photo_list'])
            {
                $user_img_list = explode(',',$item['photo_list']);
                $item['photo_list'] = $user_img_list;
                $item['user_img'] = $user_img_list[0];
            }

            // vip开通时间戳
            if ($item['is_vip'] && $item['vip_open_time']) {
                $item['is_vip_overdue'] = ($item['vip_open_time'] < time()) ? 1 : 0;//vip是否过期
                $item['vip_open_time'] = date('Y-m-d H:i:s', $item['vip_open_time']);
            }

            // 栏目认证视频
            $item['vcr'] = [];
            if ($item['is_vip_video']) {
                $findRes = $videoAuthModel->findUserVideoAuth(['user_id' => $item['user_id'],'id' => $item['is_vip_video'],'is_delete' => 0]);
                if ($findRes['errorCode'] == 0) {
                    $findRes['data']['video_url'] = strpos($findRes['data']['video_url'],'sliceVideo') !== false ? $findRes['data']['video_url'] : str_replace('upload/','upload/sliceVideo/',$findRes['data']['video_url']);
                    $item['vcr'] = $findRes['data'];
                }
            }
            // 红娘视频
            $item['red_mother_vcr'] = [];
            if ($item['is_red_mother_video'])
            {
                $findRes = $videoAuthModel->findUserVideoAuth(['user_id' => $item['user_id'],'id' => $item['is_red_mother_video'],'is_delete' => 0]);
                if ($findRes['errorCode'] == 0)
                {
                    $findRedMotherPosterImg = $configModel->findConfig(['item_key' => 'red_mother_posters_img']);
                    if ($findRedMotherPosterImg['errorCode'] == 0 && $findRedMotherPosterImg['data']['item_value']) {
                        $findRes['data']['imgs'] = $findRedMotherPosterImg['data']['item_value'];
                    }
                    $findRes['data']['video_url'] = strpos($findRes['data']['video_url'],'sliceVideo') !== false ? $findRes['data']['video_url'] : str_replace('upload/','upload/sliceVideo/',$findRes['data']['video_url']);
                    $item['red_mother_vcr'] = $findRes['data'];
                }
            }

            // 门店信息
            $item['store'] = [];
            $item['store_auth_vcr'] = [];
            if (strpos($item['identity'],'4') !== false)
            {
                $sql = <<< SQL
SELECT vcr,imgs FROM `hfztcy_store` WHERE `uid` = {$item['user_id']}
SQL;
                $res = Db::query($sql);
                if ($res && $res[0]['vcr']) {
                    $item['is_store_video'] = 1;
                    $item['store_auth_vcr'] = [
                        'video_url' => strpos($res[0]['vcr'],'sliceVideo') === false ? str_replace('upload/','upload/sliceVideo/',$res[0]['vcr']) : $res[0]['vcr'],
                        'imgs' => $res[0]['imgs']
                    ];
                }

                $res = $storeModel->findStore(['uid' => $item['user_id']]);
                if ($res['errorCode'] == 0) {
                    // 门店视频
                    if ($res['data']['vcr']) {
                        $res['data']['photo_list'] = explode(',',$res['data']['photo_list']);
                        $res['data']['vcr'] = strpos($res['data']['vcr'],'sliceVideo') === false ? str_replace('upload/','upload/sliceVideo/',$res['data']['vcr']) : $res['data']['vcr'];
                    }
                    $item['store'] = $res['data'];
                }
            }

            // 是否已收藏
            $item['is_collect'] = 0;
            $res = $collectModel->findCollect(['user_id' => $args['user_id'],'like_user_id' => $item['user_id']]);
            if ($res['errorCode'] == 0) $item['is_collect'] = 1;

            // 喜欢数/粉丝数
            $item['like_num'] = 0;
            if (isset($item['user_id']) && $item['user_id'])
            {
                $sql = <<< SQL
SELECT count(*) as num FROM `hfztcy_collect` WHERE `like_user_id` = {$item['user_id']}
SQL;
                $res = Db::query($sql);
                if ($res) $item['like_num'] = $res[0]['num'];
                $item['fans_num'] = $item['like_num'];
            }

            //1、用户通过自己搜索进入公众号之后：
            # 拨打用户电话，则拨打的是平台电话
            # 拨打红娘电话，则拨打的是对应红娘的电话
            # 拨打门店电话，则直接拨打门店电话
            //2、用户通过扫了红娘二维码进入公众号之后：
            # 拨打用户电话，则拨打的是上级红娘的电话
            # 拨打红娘电话，则拨打的是对应红娘的电话
            # 拨打门店电话，则直接拨打门店电话
            //3、用户通过扫了非红娘二维码进入公众号之后：
            # 拨打用户电话，则拨打的是平台电话
            # 拨打红娘电话，则拨打的是对应红娘的电话
            # 拨打门店电话，则直接拨打门店电话
            // 拨号规则
            // 当前登录用户是否存在推荐人
            $findUserRes = $userModel->findUser(['id' => $item['user_id']]);
            if ($findUserRes['errorCode'] == 0 && $findUserRes['data']['parent_id'])
            {
                // 推荐人身份是否红娘
                $tjr_identity = 0;
                $findParentMemberRes = $memberModel->findMember(['user_id' => $findUserRes['data']['parent_id']]);
                if ($findParentMemberRes['errorCode'] == 0) {
                    if (strpos($findParentMemberRes['data']['state'],'3') !== false) $tjr_identity = 1;
                }
                if ($tjr_identity) {
                    if ($args['state'] == 3) {//是红娘
                        $item['mobile'] = $item['my_mobile'] ?: $mobile;
                    } else if ($args['state'] == 4) {//门店
                        $item['mobile'] = $item['store'] && $item['store']['mobile'] ? $item['store']['mobile'] : $mobile;
                    } else {
                        $item['mobile'] = $findParentMemberRes['data']['mobile']?:$mobile;
                    }
                } else {
                    if ($args['state'] == 3) {//是红娘
                        $item['mobile'] = $item['my_mobile'] ?: $mobile;
                    } else if ($args['state'] == 4) {//门店
                        $item['mobile'] = $item['store'] && $item['store']['mobile'] ? $item['store']['mobile'] : $mobile;
                    } else {
                        $item['mobile'] = $mobile;
                    }
                }
            } else {// 没有推荐人
                if ($args['state'] == 3) {//是红娘
                    $item['mobile'] = $item['my_mobile'] ?: $mobile;
                } else if ($args['state'] == 4) {//门店
                    $item['mobile'] = $item['store'] && $item['store']['mobile'] ? $item['store']['mobile'] : $mobile;
                } else {
                    $item['mobile'] = $mobile;
                }
            }
        }

        return $result;
    }

    /**
     * Info: 会员信息
     * Date: 2022/11/17 15:33
     * @param $user_id int 当前浏览的用户ID
     */
    public function getMemberInfo ($user_id)
    {
        $register = 0;
        $is_guest = false;//是否游客
        $memberModel = new \app\common\model\hfztcy\LibMember();
        $wxUserModel = new LibUser();
        $findMemberRes = $memberModel->findMember(['user_id' => $user_id]);
        if ($findMemberRes['errorCode'] == 1) {//未注册
            $findWxUserRes = $wxUserModel->findUser(['id' => $user_id]);
            if ($findWxUserRes['errorCode'] == 0 && strpos($findWxUserRes['data']['identity'],'0') !== false) {
                $is_guest = true;
            }
        } else {
            $register = 1;
        }

        if ($is_guest) {
            $querySql = <<< SQL
SELECT * 
FROM `base_user` AS a 
WHERE `id` = {$user_id} LIMIT 1
SQL;
        } else {
            $where = "`user_id` = {$user_id}";
            $querySql = <<< SQL
SELECT * 
FROM (
    SELECT a.*,b.nick_name,b.identity,b.head_img_url,b.parent_id,b.account openid
    FROM `hfztcy_user` `a` 
        LEFT JOIN `base_user` `b` ON `a`.`user_id`=`b`.`id` 
) AS a 
WHERE {$where} LIMIT 1
SQL;
        }
        $result = Db::query($querySql);
        $item = $result[0];
        if ($item) {
            // 是否注册
            $item['register'] = $register;

            // 上级用户
            $item['parent_user'] = [];
            if (isset($item['parent_id']) && $item['parent_id']) {
                $parent_user_id = $item['parent_id'];
            } else {
                $parent_user_id = 152;//总部号
            }
            $sql = "SELECT a.mobile,b.id,b.nick_name,b.identity,b.head_img_url,b.parent_id
        FROM `hfztcy_user` `a` 
        LEFT JOIN `base_user` `b` ON `a`.`user_id`=`b`.`id` 
        WHERE `b`.`id` = {$parent_user_id}";
            $query = Db::query($sql);
            if ($query) {
                $parentUser = $query[0];
                $parent_user_identity = $parentUser['identity'];
                $item['parent_user']['nick_name'] = $parentUser['nick_name'];
                $item['parent_user']['head_img_url'] = $parentUser['head_img_url'];
                $item['parent_user']['mobile'] = '';
                if ($parent_user_id == 152 || strpos($parent_user_identity,'3') !== false) {
                    $item['parent_user']['mobile'] = $parentUser['mobile'];
                }
            }

            // 会员身份
            $memberIdentity = [
                '游客',
                '注册用户',
                'vip会员',
                '红娘',
                '门店'
            ];
            // 身份
            $identityList = explode(',', $item['identity']);
            $identityList = array_map('intval', $identityList);
            foreach ($memberIdentity as $k => $v) {
                if (!in_array($k, $identityList)) {
                    unset($memberIdentity[$k]);
                }
            }
            $item['identity_text'] = implode("<br/>", $memberIdentity);
            $item['identity_list'] = array_values($memberIdentity);

            // 手机号码
            $item['my_mobile'] = $item['mobile'];

            // 获取配置信息
            $configModel = new LibConfig();
            $findConfigRes = $configModel->findConfig(['item_key' => 'platform_mobile']);
            $mobile = $findConfigRes['data']['item_value'];//平台电话

            if ($parent_user_id == 152) {//总部ID
                $item['parent_user']['mobile'] = $mobile;//总部电话
            }

            $item['mobile'] = $mobile;

            // 默认照片
            if (isset($item['photo_list']) && $item['photo_list']) {
                $user_img_list = explode(',',$item['photo_list']);
                $user_img_list = array_map(function ($path) use ($user_img_list) {
                    if (!file_exists(ROOT_PATH.'public/'.$path)) {
                        unset($user_img_list[$path]);
                    } else {
                        return $path;
                    }
                },$user_img_list);
                $item['photo_list'] = array_values(array_filter($user_img_list));
            }

            // vip到期时间
            (isset($item['vip_open_time']) && $item['vip_open_time']) && $item['vip_open_time'] = date('Y-m-d H:i:s', $item['vip_open_time']);

            // 是否已收藏
            $item['is_collect'] = 0;
            $collectModel = new LibCollect();
            $res = $collectModel->findCollect(['user_id' => $user_id,'like_user_id' => $item['user_id']]);
            if ($res['errorCode'] == 0) $item['is_collect'] = 1;

            // 喜欢数/粉丝数
            $item['like_num'] = 0;
            $item['fans_num'] = 0;
            if (isset($item['user_id']) && $item['user_id'])
            {
                // 喜欢数
                $sql = <<< SQL
SELECT count(*) as num FROM `hfztcy_collect` WHERE `user_id` = {$item['user_id']}
SQL;
                $res = Db::query($sql);
                if ($res) $item['fans_num'] = $res[0]['num'];
                // 粉丝数
                $sql = <<< SQL
SELECT count(*) as num FROM `hfztcy_collect` WHERE `like_user_id` = {$item['user_id']}
SQL;
                $res = Db::query($sql);
                if ($res) $item['like_num'] = $res[0]['num'];
            }

            // 栏目认证视频
            $videoAuthModel = new LibUserVideoAuth();
            $item['vcr'] = [];
            if (isset($item['is_vip_video']) && $item['is_vip_video']) {
                $findRes = $videoAuthModel->findUserVideoAuth(['user_id' => $item['user_id'],'id' => $item['is_vip_video'],'is_delete' => 0]);
                if ($findRes['errorCode'] == 0) {
                    $findRes['data']['video_url'] = str_replace('upload/','upload/sliceVideo/',$findRes['data']['video_url']);
                    $item['vcr'] = $findRes['data'];
                }
            }
            // 红娘视频
            $item['red_mother_vcr'] = [];
            if (isset($item['is_red_mother_video']) && $item['is_red_mother_video'])
            {
                $findRes = $videoAuthModel->findUserVideoAuth(['user_id' => $item['user_id'],'id' => $item['is_red_mother_video'],'is_delete' => 0]);
                if ($findRes['errorCode'] == 0) {
                    $findRedMotherPosterImg = $configModel->findConfig(['item_key' => 'red_mother_posters_img']);
                    if ($findRedMotherPosterImg['errorCode'] == 0 && $findRedMotherPosterImg['data']['item_value']) {
                        $findRes['data']['imgs'] = $findRedMotherPosterImg['data']['item_value'];
                    }
                    $findRes['data']['video_url'] = str_replace('upload/','upload/sliceVideo/',$findRes['data']['video_url']);
                    $item['red_mother_vcr'] = $findRes['data'];
                }
            }

            // 门店信息
            $storeModel = new LibStore();
            $item['store'] = [];
            $item['store_auth_vcr'] = [];
            $item['store_parent_user'] = [];
            if (strpos($item['identity'],'4') !== false)
            {
                $sql = <<< SQL
SELECT vcr,imgs FROM `hfztcy_store` WHERE `uid` = {$item['user_id']}
SQL;
                $res = Db::query($sql);
                if ($res) {
                    $item['is_store_video'] = 1;
                    $item['store_auth_vcr'] = [
                        'video_url' => strpos($res[0]['vcr'],'sliceVideo') !== false ? $res[0]['vcr'] : str_replace('upload/','upload/sliceVideo/',$res[0]['vcr']),
                        'imgs' => $res[0]['imgs']
                    ];
                }

                $res = $storeModel->findStore(['uid' => $item['user_id']]);
                if ($res['errorCode'] == 0)
                {
                    // 门店视频
                    $res['data']['photo_list'] = explode(',',$res['data']['photo_list']);
                    $res['data']['vcr'] = strpos($res['data']['vcr'],'sliceVideo') !== false ? $res['data']['vcr'] : str_replace('upload/','upload/sliceVideo/',$res['data']['vcr']);
                    $item['store'] = $res['data'];

                    $userModel = new LibUser();
                    $findUserRes = $userModel->findUser(['id' => $item['user_id']]);
                    if ($findUserRes['errorCode'] == 0) {
                        $item['store_parent_user']['nick_name'] = $findUserRes['data']['nick_name'];
                        $item['store_parent_user']['head_img_url'] = $findUserRes['data']['head_img_url'];
                        $item['store_parent_user']['mobile'] = '';
                        $findMemberUserRes = $memberModel->findMember(['user_id' => $item['user_id']]);
                        if ($findMemberUserRes['errorCode'] == 0) {
                            $item['store_parent_user']['mobile'] = $findMemberUserRes['data']['mobile'];
                        }
                    }
                }
            }


            //1、用户通过自己搜索进入公众号之后：
            # 拨打用户电话，则拨打的是平台电话
            # 拨打红娘电话，则拨打的是对应红娘的电话
            # 拨打门店电话，则直接拨打门店电话
            //2、用户通过扫了红娘二维码进入公众号之后：
            # 拨打用户电话，则拨打的是上级红娘的电话
            # 拨打红娘电话，则拨打的是对应红娘的电话
            # 拨打门店电话，则直接拨打门店电话
            //3、用户通过扫了非红娘二维码进入公众号之后：
            # 拨打用户电话，则拨打的是平台电话
            # 拨打红娘电话，则拨打的是对应红娘的电话
            # 拨打门店电话，则直接拨打门店电话
            // 拨号规则
            $findUserRes = $wxUserModel->findUser(['id' => $user_id]);
            if ($findUserRes['errorCode'] == 0)
            {
                //当前被浏览用户身份
                $identity = 0;//用户
                if (strpos($findUserRes['data']['identity'],'3') !== false) {
                    $identity = 1;//红娘
                } else if (strpos($findUserRes['data']['identity'],'4') !== false) {
                    $identity = 2;//门店
                }

                if ($is_guest) {//游客
                    if ($identity == 1) {//是红娘
                        $item['mobile'] = $item['my_mobile'] ?: $mobile;
                    } else if ($identity == 2) {//门店
                        $item['mobile'] = $item['store'] && $item['store']['mobile'] ? $item['store']['mobile'] : $mobile;
                    } else {
                        $item['mobile'] = $mobile;
                    }
                } else {
                    // 当前登录用户是否存在推荐人
                    if ($findUserRes['data']['parent_id'])
                    {
                        // 推荐人身份是否红娘
                        $tjr_identity = 0;
                        $findParentMemberRes = $memberModel->findMember(['user_id' => $findUserRes['data']['parent_id']]);
                        if ($findParentMemberRes['errorCode'] == 0) {
                            if (strpos($findParentMemberRes['data']['state'],'3') !== false) $tjr_identity = 1;
                        }
                        if ($tjr_identity) {
                            if ($identity == 1) {//是红娘
                                $item['mobile'] = $item['my_mobile'] ?: $mobile;
                            } else if ($identity == 2) {//门店
                                $item['mobile'] = $item['store'] && $item['store']['mobile'] ? $item['store']['mobile'] : $mobile;
                            } else {
                                $item['mobile'] = $findParentMemberRes['data']['mobile'];
                            }
                        } else {
                            if ($identity == 1) {//是红娘
                                $item['mobile'] = $item['my_mobile'] ?: $mobile;
                            } else if ($identity == 2) {//门店
                                $item['mobile'] = $item['store'] && $item['store']['mobile'] ? $item['store']['mobile'] : $mobile;
                            } else {
                                $item['mobile'] = $mobile;
                            }
                        }
                    } else {// 没有推荐人
                        if ($identity == 1) {//是红娘
                            $item['mobile'] = $item['my_mobile'] ?: $mobile;
                        } else if ($identity == 2) {//门店
                            $item['mobile'] = $item['store'] && $item['store']['mobile'] ? $item['store']['mobile'] : $mobile;
                        } else {
                            $item['mobile'] = $mobile;
                        }
                    }
                }
            }
        }

        return $item;
    }
}

?>